package com.lz.timer.an.ddjobs.simple;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lz.common.util.DateUtil;
import com.lz.timer.an.entity.DspCampaign;
import com.lz.timer.an.entity.DspOutdoorsInventory;
import com.lz.timer.an.entity.DspOutdoorsStall;
import com.lz.timer.an.entity.DspPutUnit;
import com.lz.timer.an.entity.FinAccount;
import com.lz.timer.an.entity.FinBill;
import com.lz.timer.an.entity.FinUnitAccount;
import com.lz.timer.an.enums.CampaignStatusEnum;
import com.lz.timer.an.enums.DspOutdoorsStallStatusEnum;
import com.lz.timer.an.enums.DspPutUnitStatusEnum;
import com.lz.timer.an.enums.FinBillTypeEnum;
import com.lz.timer.an.service.DspCampaignService;
import com.lz.timer.an.service.DspOutdoorsInventoryService;
import com.lz.timer.an.service.DspOutdoorsStallService;
import com.lz.timer.an.service.DspPutUnitService;
import com.lz.timer.an.service.FinAccountService;
import com.lz.timer.an.service.FinBillService;
import com.lz.timer.an.service.FinUnitAccountService;

import lombok.extern.slf4j.Slf4j;

/**
 * 单元暂停
 *
 * @author rench
 */
@Slf4j
public class StatisticalCellPauseJob implements SimpleJob {

	@Autowired
	private DspCampaignService dspCampaignService;

	@Autowired
	private DspOutdoorsStallService dspOutdoorsStallservice;

	@Autowired
	private DspOutdoorsInventoryService dspOutdoorsInventoryService;

	@Autowired
	private FinBillService finBillService;

	@Autowired
	private FinUnitAccountService finUnitAccountService;

	@Autowired
	private FinAccountService finAccountService;

	@Autowired
	private DspPutUnitService dspPutUnitService;

	@Override
	public void execute(final ShardingContext context) {

		long threadId = Thread.currentThread().getId();

		int result = 0;
		// 当前分片
		int item = context.getShardingItem();

		log.info("SIMPLE Thread:{}, ShardingContext:{}", threadId, context.toString());
		switch (item) {
		case 0:

			log.info("==========================begin=============================");
			log.info("++++++++++++++++单元暂停 ，超过3天未投放，+++++++++++++++++");

			// 遍历 推广计划表 状态复审待上刊， 时间差一天。 记录推广计划中的 dsp_id
			// 便利广告计划表。
			Map<String, Object> queryMap = new HashMap<String, Object>();
			String dateStr = DateUtil.formatDate(DateUtil.minusDays(new Date(), 3), "yyyy-MM-dd HH:mm:ss");

			//// 判断状态， 初审 复审 不通过的 并且时间 跟今天相差一天， 存储到List中
			// 时间小于等于这个时间，并且状态在eq_status中， 则符合条件
			queryMap.put("stop_time", dateStr);
			queryMap.put("status", DspPutUnitStatusEnum.STOP.getValue());
			List<DspPutUnit> dspPutUnitList = dspPutUnitService.selectListByMap(queryMap);

			 log.info("thread:{} 单元暂停-超过3天未启用, queryMap:{}, dspPutUnitList:{}", threadId, queryMap, dspPutUnitList);
			// 推广计划变更 未投放
			for (DspPutUnit dspPutUnit : dspPutUnitList) {

				String campaignNo = dspPutUnit.getCampaign_no();

				// 查询推广计划
				queryMap.clear();
				queryMap.put("campaign_no", campaignNo);

				DspCampaign dspCampaign = dspCampaignService.selectOneByMap(queryMap);
				log.info("thread:{} 查询单元所在推广计划, queryMap:{}, dspPutUnit:{}, dspCampaign:{}", threadId, queryMap, dspPutUnit, dspCampaign);

				Long dspId = dspCampaign.getDsp_user_id();
				String campaignNoStr = dspCampaign.getCampaign_no();
				BigDecimal campaignSumVaule = new BigDecimal("0");

				// 查询用户账户表
				FinAccount finAccount = finAccountService.selectOneByPK(dspId);

				dspCampaign.setStatus(CampaignStatusEnum.NOT_PUT_IN.getValue());
				dspCampaignService.update(dspCampaign);

				queryMap.clear();
				queryMap.put("campaign_no", campaignNoStr);
				queryMap.put("status", DspOutdoorsStallStatusEnum.FILING_STATUS.getValue());

				List<DspOutdoorsStall> dspOutdoorsStallList = dspOutdoorsStallservice.selectListByMap(queryMap);

				log.info("thread:{} 执行操作：删除占档 信息", threadId);
				for (DspOutdoorsStall dspOutdoorsStall : dspOutdoorsStallList) {

					Long id = dspOutdoorsStall.getId();
					dspOutdoorsStallservice.deleteByPK(id);

					queryMap.clear();
					queryMap.put("udid", dspOutdoorsStall.getUdid());
					queryMap.put("ssp_ad_slot_rtb_id", dspOutdoorsStall.getSsp_ad_slot_rtb_id());

					List<DspOutdoorsInventory> dspOutdoorsInventorieList = dspOutdoorsInventoryService
							.selectListByMap(queryMap);
					for (DspOutdoorsInventory dspOutdoorsInventory : dspOutdoorsInventorieList) {

						log.info("thread:{} 开始清库存， 清理前dspOutdoorsInventory:{}", threadId, dspOutdoorsInventory);

						Long inventory = dspOutdoorsInventory.getInventory();
						Long occupy_inventory = dspOutdoorsInventory.getOccupy_inventory();

						dspOutdoorsInventory.setInventory(inventory + occupy_inventory);
						dspOutdoorsInventory.setOccupy_inventory(0L);

						dspOutdoorsInventoryService.update(dspOutdoorsInventory);
					}

				}

				// 单元账户
				queryMap.clear();
				queryMap.put("campaign_no", campaignNoStr);
				List<FinUnitAccount> finUnitAccountList = finUnitAccountService.selectListByMap(queryMap);

				// campaignSumVaule
				log.info("thread:{} 执行操作：单元账户退款操作", threadId);
				for (FinUnitAccount finUnitAccount : finUnitAccountList) {

					BigDecimal frozenAmount = finUnitAccount.getFrozen_amount();

					finUnitAccount.setRefund(frozenAmount);
					finUnitAccount.setFrozen_amount(new BigDecimal(0));

					finUnitAccountService.update(finUnitAccount);

					FinBill finBill = new FinBill();
					finBill.setAccount_id(finUnitAccount.getId());
					finBill.setAmount(frozenAmount);
					finBill.setCash_surplus(frozenAmount.add(finAccount.getAmount()));

					try {
						InetAddress addr = InetAddress.getLocalHost();
						finBill.setClient_ip(addr.getHostAddress());
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					finBill.setCreate_user(0L);
					finBill.setCreate_user_name("复审通过一天未投放");
					finBill.setCreate_time(new Date());
					finBill.setDetail_id(0L);

					finBill.setDsp_user_id(finAccount.getDsp_user_id());
					finBill.setDsp_user_name(finAccount.getDsp_user_name());
					finBill.setOper_type(FinBillTypeEnum.FROZEN_TYPE.getValue());

					log.info("thread:{} 执行操作：新增账单信息", threadId);
					finBillService.insert(finBill);

					campaignSumVaule.add(frozenAmount);
				}

				BigDecimal frozenAmount = finAccount.getFrozen_amount();
				BigDecimal amount = finAccount.getAmount();

				finAccount.setAmount(amount.add(campaignSumVaule));
				finAccount.setFrozen_amount(frozenAmount.subtract(campaignSumVaule));

				log.info("thread:{} 执行操作：更新用户账户信息", threadId);
				finAccountService.update(finAccount);
			}

			log.info("====================+======end=================+============");

			break;
		default:
			log.warn("not total job, item:{}, Thread:{}", item, threadId);
			return;
		}

		log.info("job ：time = {} SIMPLE Thread:{}, result:{}, end", new Date(), threadId, result);

	}

}